package ynu.edu.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

@Configuration
public class GlobalCorsConfig {

    @Bean
    public CorsWebFilter corsFilter() {
        // 创建CORS配置对象
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedOrigin("*");             // 允许的来源
        config.addAllowedMethod("*");             // 允许所有HTTP方法（GET/POST等）
        config.addAllowedHeader("*");             // 允许所有请求头
        config.setAllowCredentials(true);          // 允许携带凭证（如cookies）
        config.addAllowedMethod("OPTIONS");
        config.addExposedHeader("Authorization"); // 允许客户端获取的响应头
        // 注册配置到所有路径
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config); // 应用于所有路由

        return new CorsWebFilter(source);
    }
}